#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import pika
import uuid


class FibonacciRpcClient(object):
    def __init__(self):
        # 建立连接
        self.connection = pika.BlockingConnection(
            pika.ConnectionParameters(host='192.168.122.173'))
        # 建立通道
        self.channel = self.connection.channel()
        # 3.声明rpc-server ---> rpc-client 的 amq.gen
        result = self.channel.queue_declare(queue='', exclusive=True)  # amq.gen-5N69yyWCpKYpQ7qBsjB4Fw
        self.callback_queue = result.method.queue  # amq.gen-5N69yyWCpKYpQ7qBsjB4Fw
        # 4.客户端监听 amq.gen 这个队列中获取
        self.channel.basic_consume(
            queue=self.callback_queue,
            on_message_callback=self.on_response,
            auto_ack=True)
        self.response = None
        self.corr_id = None

    def on_response(self, ch, method, props, body):
        if self.corr_id == props.correlation_id:
            self.response = body

    def call(self, n):
        self.response = None
        self.corr_id = str(uuid.uuid4())
        # 5.向 rpc_queue 队列推送消息
        self.channel.basic_publish(
            exchange='',
            routing_key='rpc_queue',
            properties=pika.BasicProperties(
                reply_to=self.callback_queue,  # amq.gen-5N69yyWCpKYpQ7qBsjB4Fw
                correlation_id=self.corr_id,
            ),
            body=str(n))
        self.connection.process_data_events(time_limit=None)
        return int(self.response)


fibonacci_rpc = FibonacciRpcClient()
print(" [x] Requesting fib(30)")
response = fibonacci_rpc.call(30)
print(" [.] Got %r" % response)
